import 'dart:async';
import 'dart:io';

import 'package:center_beijing/api/authorization_api.dart';
import 'package:center_beijing/api/factory_api.dart';
import 'package:center_beijing/common/QRScan.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:encrypt/encrypt.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:orientation/orientation.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';

import 'api/component_api.dart';
import 'api/material_science_api.dart';
import 'api/task_api.dart';
import 'common/custom_floatingAction_buttonLocation.dart';
import 'common/logutil.dart';
import 'package:url_launcher/url_launcher.dart';
// import 'package:device_info_plus/device_info_plus.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
  final List<Tab> myTabs = <Tab>[
    Tab(text: '我的任务'),
    Tab(text: '我发起的'),
  ];
  var WIDTH = (1.sw - 80.w) / 5;
  TabController _tabController;
  int currentIndex = 0;
  List tem = [
    'ComprehensiveData',
    'ProductManage',
    'StorageManager',
    'TransPortManager',
    'QualityInspection',
    'QualityVerification',
    'SafetyInspection',
    'EquipmentInspection',
    'OnlineEducation',
    'IntegralConsumption',
    'ProductSetting',
    'SpaceOperationHistory',
    'WorkPermitList'
  ];
  List tem2 = [
    'hiddenDanger',
    'QualityProblem',
    'EquipmentProblems',
    'RequisitionApplication',
    'ComponentScrapping',
    'MaterialWarehousing',
    'EquipmentMaintenance',
    'EquipmentUse',
    'ReturnsManagement',
    'WorkPermit',
    'SpaceOperation'
  ];
  List menu = [];
  List menu2 = [];
  List taskTypeList = ['全部任务', '设备巡检', '质量巡检', '安全巡检'];
  var selectTaskType = '全部任务';
  List userHandleList = [];
  List userCreateList = [];
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;

  static Future<String> encodeString(String content) async {
    var publicKeyStr =
        await rootBundle.loadString('assets/data/rsa_public_key.pem');
    var publicKey = RSAKeyParser().parse(publicKeyStr);
    final encrypter = Encrypter(RSA(publicKey: publicKey));
    return encrypter.encrypt(content).base64;
  }

  @override
  void initState() {
    super.initState();
    this.getWarehouse();
    this.getFlow();
    this.getCreateFlow();
    bus.on('refreshHome', (arg) {
      this.getFlow();
      this.getCreateFlow();
      this.getAllMenu();
    });
    bus.on('refreshTitle', (arg) {
      this.getFlow();
      this.getCreateFlow();
      this.getAllMenu();
    });
    // const timeout = const Duration(seconds: 15);
    // Timer.periodic(timeout, (timer) { //callback function
    //   //1s 回调一次
    //   print('afterTimer='+DateTime.now().toString());
    //   this.getFlow(); // 取消定时器
    // });
    this.getAllMenu();
    this.getCurrentVersion();
  }

  getCurrentVersion() async {
    var result = await getAppVersion({});
    if (result != null) {
      if (Platform.isAndroid) {
        if (result[0]['code'] != GlobalConfig.version) {
          showDialog(
              barrierDismissible: false,
              context: this.context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text('注意'),
                  content: Text('有新版本更新,点击确定更新版本！'),
                  actions: <Widget>[
                    new Container(
                      child: FlatButton(
                        child: new Text(
                          "取消",
                          style: TextStyle(color: Colors.black),
                        ),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                    ),
                    new Container(
                      child: FlatButton(
                        child: new Text(
                          "确定",
                          style: TextStyle(color: Colors.red),
                        ),
                        onPressed: () {
                          Navigator.pop(context);
                          launch(
                              'http://www.sinoccdc.com/app/zps/install.html');
                        },
                      ),
                    ),
                  ],
                );
              });
        }
      }
    }
    LogUtil.d(result);
  }

  /*
  * 获取工厂所有仓库和
  * */
  getWarehouse() async {
    LogUtil.d(GlobalConfig.selectFactory.value);
    var result = await getAllWarehouse(GlobalConfig.selectFactory.value);
    if (result != null) {
      GlobalConfig.warehouseList = result;
    }
    LogUtil.d(result);
  }

  getAllMenu() {
    menu2 = [];
    menu = [];
    GlobalConfig.jurisdiction.forEach((element) {
      if (tem.contains(element['appFunction']['className'])) {
        menu.add(element);
      } else if (tem2.contains(element['appFunction']['className'])) {
        menu2.add(element);
      }
    });
    this.setState(() {});
  }

/*
  * 获取任务列表
  * */
  getFlow() async {
    var result = await getUserWorkflow({
      'tenantId': GlobalConfig.tenantId,
      'tenantSubTypeId': GlobalConfig.selectFactory.tag,
      'page': page,
      'limit': 400,
    });
    if (result != null &&
        result['results'] != null &&
        result['results'].length > 0) {
      this.setState(() {
        userHandleList = result['results'];
        firstLoad = false;
      });
    } else {
      this.setState(() {
        userHandleList = [];
        firstLoad = false;
      });
    }
  }

  updateRead(businessId) async {
    var result = await changeRead({'recordId': businessId});
    if (result != null) {
    } else {}
  }

  /*
  * 获取发起的任务列表
  * */
  getCreateFlow() async {
    var result = await getUserCreate({
      'tenantId': GlobalConfig.tenantId,
      'tenantSubTypeId': GlobalConfig.selectFactory.tag,
      'pageIndex': 0,
      'limit': 400,
      'userId': GlobalConfig.userInfo['userId'],
    });
    if (result != null &&
        result['results'] != null &&
        result['results'].length > 0) {
      var list = [];
      result['results'].forEach((element) {
        if (element['businessType'] == 'TBMC_QS_CHECK_RECORD' ||
            element['businessType'] == 'TBMC_ELEMENT_SCRAP_INFO') {
          list.add(element);
        }
      });
      this.setState(() {
        userCreateList = result['results'];
        firstLoad = false;
      });
    } else {
      this.setState(() {
        userCreateList = [];
        firstLoad = false;
      });
    }
  }

  /*
  * 领料单审批
  * */
  saveRequisition(type, value1, value2) async {
    var pass = {
      'acceptStatus': type,
      'acceptItemId': value2['businessId'],
      'taskId': value1['taskId']
    };
    var result = await saveAcceptMatRequisition(pass);
    if (result != null && result['text'] == '') {
      Fluttertoast.showToast(msg: '审批成功');
      bus.emit('refreshHome');
    }
    LogUtil.d(result);
  }

  /*
  * 获取点击后数据
  * */
  getSelect(value) async {
    var result = await getUserTaskPoint({
      'openType': '0',
      'appType ': 'app',
      'taskId': value['taskId'],
      'wfProcessDefId': value['wfProcessDefId'],
      'wfProcessInstanceId': value['wfProcessInstanceId']
    });
    if (result != null) {
      this.updateRead(result['businessId']);
      this.setState(() {
        value['isRead'] = 1;
      });
      switch (result['taskCode']) {
        case "questionQuality_Rectify":
          Get.toNamed(RouteConfig.problemRectification, arguments: {
            'businessId': result['businessId'],
            'taskId': value['taskId']
          });
          break;
        case "questionQuality_Review":
          Get.toNamed(RouteConfig.problemRecheck, arguments: {
            'businessId': result['businessId'],
            'taskId': value['taskId']
          });
          break;
        case "requisition_review":
          showDialog(
              barrierDismissible: false,
              context: this.context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text('注意'),
                  content: Text('领料单审批？'),
                  actions: <Widget>[
                    Row(
                      children: [
                        FlatButton(
                          child: new Text(
                            "取消",
                            style: TextStyle(color: Styles.DetailColor),
                          ),
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        ),
                        FlatButton(
                          child: new Text(
                            "拒绝",
                            style: TextStyle(color: Styles.RedColor),
                          ),
                          onPressed: () {
                            Navigator.pop(context);
                            this.saveRequisition('0', value, result);
                          },
                        ),
                        FlatButton(
                          child: new Text(
                            "同意",
                            style: TextStyle(color: Styles.BlueColor),
                          ),
                          onPressed: () {
                            Navigator.pop(context);

                            this.saveRequisition('1', value, result);
                          },
                        ),
                      ],
                    ),
                  ],
                );
              });
          break;
        case "questionSafe_Rectify":
          Get.toNamed(RouteConfig.safetyRectification, arguments: {
            'businessId': result['businessId'],
            'taskId': value['taskId']
          });
          break;
        case "questionSafe_Review":
          Get.toNamed(RouteConfig.safetyRecheck, arguments: {
            'businessId': result['businessId'],
            'taskId': value['taskId']
          });
          break;
        case "scrap_approve":
          Get.toNamed(RouteConfig.scrapApproval, arguments: {
            'businessId': result['businessId'],
            'taskId': value['taskId']
          });
          break;
        case "alert_approve":
          if (result['processKey'] == 'ELEMENT_ALERT_FLOW') {
            Get.toNamed(RouteConfig.specialEquipment, arguments: {
              'businessId': result['businessId'],
              'taskId': value['taskId'],
            });
          }
          break;
        case "space_work_approve_1":
          await Get.toNamed(RouteConfig.confinedSpaceDetail, arguments: {
            'businessId': value['businessId'],
            'taskId': value['taskId'],
            'taskKey': value['taskKey']
          });
          this.setState(() {});
          break;
        default:
          if (result['businessType'] == 'tbmc_confined_space_work') {
            await Get.toNamed(RouteConfig.confinedSpaceDetail2, arguments: {
              'businessId': value['businessId'],
              'taskId': value['taskId'],
              'taskKey': value['taskKey']
            });
            this.setState(() {});
          } else if (result['businessType'] == 'tbmc_cons_work_license' &&
              (result['taskCode'] == 'license_confirm' ||
                  result['taskCode'] == 'license_check' ||
                  result['taskCode'] == 'license_end')) {
            await Get.toNamed(RouteConfig.workPermitDetail, arguments: {
              'businessId': result['businessId'],
              'taskId': value['taskId'],
              'taskKey': value['taskKey']
            });
            this.setState(() {});
          } else if (result['taskCode'] == 'license_start') {
            await Get.toNamed(RouteConfig.addWorkPermit, arguments: {
              'businessId': result['businessId'],
              'taskId': value['taskId'],
              'taskKey': value['taskKey']
            });
            this.setState(() {});
          }
          break;
      }
    }
    LogUtil.d(result);
  }

  getMenuImage(item) {
    switch (item) {
      case 'ComprehensiveData':
        return 'assets/images/icon_kanban.png';
        break;
      case 'ProductManage':
        return 'assets/images/icon_shengchan.png';
        break;
      case 'StorageManager':
        return 'assets/images/icon_duichang.png';
        break;
      case 'TransPortManager':
        return 'assets/images/icon_yunshu.png';
        break;
      case 'QualityInspection':
        return 'assets/images/icon_xunjian.png';
        break;
      case 'QualityVerification':
        return 'assets/images/icon_hejian.png';
        break;
      case 'SafetyInspection':
        return 'assets/images/icon_anquan.png';
        break;
      case 'EquipmentInspection':
        return 'assets/images/icon_shebei.png';
        break;
      case 'hiddenDanger':
        return 'assets/images/icon_anquan_small.png';
        break;
      case 'QualityProblem':
        return 'assets/images/icon_zhiliang_small.png';
        break;
      case 'EquipmentProblems':
        return 'assets/images/icon_shebei_small.png';
        break;
      case 'RequisitionApplication':
        return 'assets/images/icon_shenqing_small.png';
        break;
      case 'MaterialWarehousing':
        return 'assets/images/icon_shenqing_small.png';
        break;
      case 'ComponentScrapping':
        return 'assets/images/icon_baofei_small.png';
        break;
      case 'OnlineEducation':
        return 'assets/images/icon_jiaoyu.png';
        break;
      default:
        return 'assets/images/icon_shebei_small.png';
    }
  }

  /*
  * 获取列表类型
  * */
  getImageStatus(value) {
    switch (value) {
      case 'TBMC_QS_CHECK_RECORD':
        return 'assets/images/home_icon_zhi.png';
      case 'LITTLE_MAT_REQUISITION':
        return 'assets/images/home_icon_liao.png';
      case 'TBMC_ELEMENT_SCRAP_INFO':
        return 'assets/images/home_icon_fei.png';
      default:
        return 'assets/images/home_icon_she.png';
    }
  }

  @override
  void dispose() {
    bus.off('refreshHome');
    bus.off('refreshTitle');
    super.dispose();
  }

  Widget getMenu(item) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        this.menuClick(item['className']);
      },
      child: Container(
        alignment: Alignment.center,
        width: ((1.sw - 80.w) / 4),
        padding: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, Styles.spacing8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              this.getMenuImage(item['className']),
              width: 30.w,
              height: 30.h,
              fit: BoxFit.contain,
            ),
            Container(
              padding:
                  EdgeInsets.fromLTRB(0, Styles.spacing4, 0, Styles.spacing4),
              child: Text(
                item['funcName'],
                style: TextStyle(
                    color: Styles.DetailColor, fontSize: Styles.NormalFont),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget getMenu2(item) {
    return GestureDetector(
      onTap: () {
        this.menuClick(item['className']);
      },
      child: Container(
        margin: EdgeInsets.fromLTRB(Styles.spacing4, 0, Styles.spacing4, 0),
        alignment: Alignment.center,
        width: ((1.sw - 80.w) / 4),
        padding: EdgeInsets.fromLTRB(
            Styles.spacing4, Styles.spacing8, Styles.spacing4, Styles.spacing8),
        decoration: BoxDecoration(
            border: Border.all(color: Styles.GranColor, width: 1)),
        child: Column(
          children: [
            Image.asset(
              this.getMenuImage(item['className']),
              height: 20.h,
              width: 20.w,
              fit: BoxFit.fill,
            ),
            Text(
              '填报',
              style: TextStyle(
                  color: Styles.DetailColor, fontSize: Styles.NormalFont),
            ),
            Text(
              item['funcName'],
              style: TextStyle(
                  color: Styles.DetailColor, fontSize: Styles.SmallFont),
            )
          ],
        ),
      ),
    );
  }

  menuClick(item) async {
    switch (item) {
      case 'ComprehensiveData':
        Get.toNamed(RouteConfig.comprehensiveData);
        break;
      case 'ProductManage':
        Get.toNamed(RouteConfig.productionManagement);
        break;
      case 'StorageManager':
        Get.toNamed(RouteConfig.storageManagement);
        break;
      case 'TransPortManager':
        Get.toNamed(RouteConfig.transportationManagement);
        break;
      case 'QualityInspection':
        Get.toNamed(RouteConfig.qualityInspection);
        break;
      case 'QualityVerification':
        Get.toNamed(RouteConfig.qualityVerification);
        break;
      case 'SafetyInspection':
        Get.toNamed(RouteConfig.sageTyInspection);
        break;
      case 'EquipmentInspection':
        Get.toNamed(RouteConfig.equipmentTasks);
        break;
      case 'SpaceOperationHistory':
        Get.toNamed(RouteConfig.confinedSpaceHistory);
        break;
      case 'WorkPermitList':
        Get.toNamed(RouteConfig.workPermitList);
        break;

      case 'hiddenDanger':
        Get.toNamed(RouteConfig.addSafetyProblem);
        break;
      case 'QualityProblem':
        Get.toNamed(RouteConfig.addQuality);
        break;
      case 'EquipmentProblems':
        Get.toNamed(RouteConfig.equipmentProblemReport);
        break;
      case 'RequisitionApplication':
        Get.toNamed(RouteConfig.materialRequisitionList);
        break;
      case 'MaterialWarehousing':
        Get.toNamed(RouteConfig.materialWarehousing);
        break;
      case 'ComponentScrapping':
        Get.toNamed(RouteConfig.componentScrap);
        break;
      case 'OnlineEducation':
        break;
      case 'EquipmentMaintenance': //设备维修
        Get.toNamed(RouteConfig.equipmentMaintenanceReport);
        break;
      case 'EquipmentUse': //设备使用
        Get.toNamed(RouteConfig.equipmentUse);
        break;
      case 'ReturnsManagement': //退货管理
        Get.toNamed(RouteConfig.returnProduction);
        break;
      case "IntegralConsumption":
        this.jumpScan();
        break;
      case "ProductSetting":
        Get.toNamed(RouteConfig.productSetting);
        break;
      case "WorkPermit":
        await Get.toNamed(RouteConfig.addWorkPermit);
        this.setState(() {});
        break;
      case "SpaceOperation":
        await Get.toNamed(RouteConfig.addConfinedSpace);
        this.setState(() {});
        break;
      default:
        break;
    }
  }

  jumpScan() async {
    var result = await QrScan.scan(context, type: 3);
    if (result != null) {
      if (result is String &&
          result.contains('employeeId')) {
        Uri u = Uri.parse(result.replaceAll('#/', ''));
        Get.toNamed(RouteConfig.addConsumption,
            arguments: u.queryParameters['employeeId']);
      } else {
        showDialog(
            barrierDismissible: false,
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text('注意'),
                content: Text('请扫正确的二维码！'),
                actions: <Widget>[
                  new Container(
                    child: FlatButton(
                      child: new Text(
                        "确定",
                        style: TextStyle(color: Colors.red),
                      ),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                ],
              );
            });
      }
    }
  }

  DateTime lastPopTime;

  @override
  Widget build(BuildContext context) {
    if (currentIndex == 0) {
      dataSource = userHandleList;
    } else {
      dataSource = userCreateList;
    }
    return WillPopScope(
        child: Scaffold(
            appBar: AppBar(
              title: Text.rich(TextSpan(children: [
                WidgetSpan(
                    child: Padding(
                  padding: EdgeInsets.fromLTRB(5, 0, 5, 2),
                  child: Image(
                    image: AssetImage('assets/images/logo.png'),
                    width: 20.w,
                    height: 20.h,
                    fit: BoxFit.contain,
                  ),
                )),
                TextSpan(text: GlobalConfig.selectFactory.label)
              ])),
              actions: [
                GestureDetector(
                  onTap: () {
                    Get.toNamed(RouteConfig.me);
                  },
                  child: Container(
                    padding: EdgeInsets.fromLTRB(0, 0, Styles.spacing16, 0),
                    child: Image.asset(
                      "assets/images/person.png",
                      width: 16.w,
                      height: 16.h,
                      fit: BoxFit.contain,
                    ),
                  ),
                )
              ],
            ),
            body: Container(
              constraints: BoxConstraints.expand(),
              color: Styles.MainBackgroundColor,
              padding: EdgeInsets.fromLTRB(
                  0, 0, 0, MediaQuery.of(context).padding.bottom),
              child: EasyRefresh(
                  header: ClassicalHeader(
                    refreshingText: '刷新中...',
                    refreshText: '下拉刷新...',
                    infoText:
                        "最后更新${DateTime.now().hour}:${DateTime.now().minute < 10 ? "0" : ""}${DateTime.now().minute}",
                    refreshReadyText: "放开刷新...",
                    refreshedText: '刷新完成',
                  ),
                  onRefresh: () async {
                    //下拉请求新数据
                    this.getFlow();
                    this.getCreateFlow();
                    this.getAllMenu();
                  },
                  //需要上下拉刷新的组件 这里是CustomScrollView
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Container(
                          alignment: menu.length > 3
                              ? Alignment.center
                              : Alignment.centerLeft,
                          padding: EdgeInsets.fromLTRB(10.w, 20.h, 10.w, 10.h),
                          child: Wrap(
                            spacing: 10.w, //主轴上子控件的间距
                            runSpacing: 5, //交叉轴上子控件之间的间距
                            children: this.menu.map<Widget>((item) {
                              return getMenu(item['appFunction']);
                            }).toList(), //要显示的子控件集合
                          ),
                        ),
                        menu2.length > 0
                            ? Container(
                                height: 110,
                                alignment: menu2.length > 3
                                    ? Alignment.center
                                    : Alignment.centerLeft,
                                padding:
                                    EdgeInsets.fromLTRB(10.w, 10.h, 10.w, 10.h),
                                child: ListView(
                                  scrollDirection: Axis.horizontal,
                                  children: this.menu2.map<Widget>((item) {
                                    return getMenu2(item['appFunction']);
                                  }).toList(),
                                ),
                              )
                            : Container(),
                        Container(
                          color: Colors.white,
                          margin: EdgeInsets.only(top: Styles.spacing8),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing8,
                              Styles.spacing16,
                              Styles.spacing8),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '我的任务',
                                style: TextStyle(
                                    color: Styles.DetailColor,
                                    fontSize: Styles.NormalFont),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          height: 40.h,
                          color: Colors.white,
                          child: DefaultTabController(
                            length: 2,
                            initialIndex: currentIndex,
                            child: TabBar(
                              controller: _tabController,
                              onTap: (value) {
                                this.setState(() {
                                  currentIndex = value;
                                });
                              },
                              indicatorColor: Colors.red,
                              tabs: myTabs,
                              labelColor: Styles.BlueColor,
                              unselectedLabelColor: Styles.LeftTitleColor,
                              // add it here
                              indicator: MaterialIndicator(
                                  color: Styles.BlueColor, height: 1),
                            ),
                          ),
                        ),
                        this.dataSource.length > 0
                            ? Column(
                                children:
                                    this.dataSource.asMap().keys.map((index) {
                                  return GestureDetector(
                                    onTap: () {
                                      if (currentIndex == 0) {
                                        this.getSelect(dataSource[index]);
                                      } else {
                                        if (dataSource[index]['businessType'] ==
                                            'TBMC_QS_CHECK_RECORD') {
                                          Get.toNamed(
                                              RouteConfig.problemComplete,
                                              arguments: {
                                                'businessId': dataSource[index]
                                                    ['businessId'],
                                                'taskId': dataSource[index]
                                                    ['lastTaskId']
                                              });
                                        } else if (dataSource[index]
                                                ['businessType'] ==
                                            'TBMC_ELEMENT_SCRAP_INFO') {
                                          Get.toNamed(
                                              RouteConfig.scrapApprovalDetail,
                                              arguments: {
                                                'businessId': dataSource[index]
                                                    ['businessId'],
                                                'taskId': dataSource[index]
                                                    ['lastTaskId'],
                                              });
                                        } else {
                                          // Fluttertoast.showToast(msg: '功能暂未实现');
                                        }
                                      }
                                    },
                                    child: currentIndex == 0
                                        ? Container(
                                            color: Colors.white,
                                            padding: EdgeInsets.fromLTRB(
                                                Styles.spacing16,
                                                Styles.spacing8,
                                                Styles.spacing16,
                                                Styles.spacing8),
                                            margin: EdgeInsets.fromLTRB(
                                                Styles.spacing8,
                                                Styles.spacing4,
                                                Styles.spacing8,
                                                Styles.spacing4),
                                            child: Row(
                                              children: [
                                                Container(
                                                  alignment: Alignment.center,
                                                  margin: EdgeInsets.only(
                                                      right: Styles.spacing8),
                                                  child: Image.asset(
                                                    this.getImageStatus(
                                                        dataSource[index]
                                                            ['businessType']),
                                                    width: 25.w,
                                                    height: 25.h,
                                                  ),
                                                ),
                                                Expanded(
                                                  child: Column(
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    children: [
                                                      Text.rich(TextSpan(
                                                          children: [
                                                            dataSource[index][
                                                                        'taskKey'] ==
                                                                    'questionQuality_Rectify'
                                                                ? TextSpan(
                                                                    text: dataSource[index]['isRead'] ==
                                                                            1
                                                                        ? '[已读]'
                                                                        : '[未读]',
                                                                    style: TextStyle(
                                                                        color: dataSource[index]['isRead'] ==
                                                                                1
                                                                            ? Styles
                                                                                .GrayButtonColor
                                                                            : Styles
                                                                                .RedColor,
                                                                        fontSize:
                                                                            Styles.Middle15Font))
                                                                : TextSpan(),
                                                            TextSpan(
                                                                text: dataSource[index]
                                                                            [
                                                                            'summary'] !=
                                                                        null
                                                                    ? dataSource[
                                                                            index]
                                                                        [
                                                                        'summary']
                                                                    : '--',
                                                                style: TextStyle(
                                                                    color: Styles
                                                                        .DetailColor,
                                                                    fontSize: Styles
                                                                        .Middle15Font))
                                                          ])),
                                                      Container(
                                                        margin: EdgeInsets.only(
                                                            top: Styles
                                                                .spacing8),
                                                        child: Text(
                                                          Utils.utilsTime(
                                                              this.dataSource[
                                                                      index][
                                                                  'createTime']),
                                                          style: TextStyle(
                                                              color: Styles
                                                                  .LeftTitleColor,
                                                              fontSize: Styles
                                                                  .NormalFont),
                                                        ),
                                                      )
                                                    ],
                                                  ),
                                                ),
                                              ],
                                            ),
                                          )
                                        : Container(
                                            color: Colors.white,
                                            padding: EdgeInsets.fromLTRB(
                                                Styles.spacing16,
                                                Styles.spacing8,
                                                Styles.spacing16,
                                                Styles.spacing8),
                                            margin: EdgeInsets.fromLTRB(
                                                Styles.spacing8,
                                                Styles.spacing4,
                                                Styles.spacing8,
                                                Styles.spacing4),
                                            child: Row(
                                              children: [
                                                Container(
                                                  alignment: Alignment.center,
                                                  margin: EdgeInsets.only(
                                                      right: Styles.spacing8),
                                                  child: Image.asset(
                                                    this.getImageStatus(
                                                        dataSource[index]
                                                            ['businessType']),
                                                    width: 25.w,
                                                    height: 25.h,
                                                  ),
                                                ),
                                                Expanded(
                                                  child: Column(
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    children: [
                                                      Text(
                                                        dataSource[index][
                                                                    'procInstTitle'] !=
                                                                null
                                                            ? dataSource[index][
                                                                'procInstTitle']
                                                            : '--',
                                                        style: TextStyle(
                                                            color: Styles
                                                                .DetailColor,
                                                            fontSize: Styles
                                                                .Middle15Font),
                                                      ),
                                                      Container(
                                                        margin: EdgeInsets.only(
                                                            top: Styles
                                                                .spacing8),
                                                        child: Text(
                                                          dataSource[index][
                                                                      'procInstStartTimeStr'] !=
                                                                  null
                                                              ? dataSource[
                                                                      index][
                                                                  'procInstStartTimeStr']
                                                              : '--',
                                                          style: TextStyle(
                                                              color: Styles
                                                                  .LeftTitleColor,
                                                              fontSize: Styles
                                                                  .NormalFont),
                                                        ),
                                                      )
                                                    ],
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                  );
                                }).toList(),
                              )
                            : firstLoad
                                ? Center(
                                    child: CircularProgressIndicator(),
                                  )
                                : Center(
                                    child: Image(
                                      image: AssetImage(
                                          'assets/images/no_data.png'),
                                      width: 128,
                                      height: 150,
                                    ),
                                  )
                      ],
                    ),
                  )),
            ),
            floatingActionButtonLocation: CustomFloatingActionButtonLocation(
              FloatingActionButtonLocation.endFloat,
            ),
            floatingActionButtonAnimator: NoScalingAnimation(),
            floatingActionButton: FloatingActionButton(
                child: Image.asset(
                  'assets/images/saoyisao.png',
                  fit: BoxFit.fill,
                ),
                onPressed: () async {
                  // Get.toNamed(RouteConfig.equipmentDetail,
                  //               arguments: '8a8b03127df9b96d017e0f1e52000000');
                  var result = await QrScan.scan(context, type: 3);
                  if (result != null) {
                    if (result is String && result.contains('rehaview/share')) {
                      var phone = await encodeString(
                          GlobalConfig.userInfo['userName'] +
                              ',' +
                              GlobalConfig.userInfo['name']);
                      launch(result + '/' + phone);
                    } else if (result is String &&
                        result.contains('employeeId')) {
                      Uri u = Uri.parse(result.replaceAll('#/', ''));
                      Get.toNamed(RouteConfig.addConsumption,
                          arguments: u.queryParameters['employeeId']);
                    } else {
                      if (result['type'] == 1) {
                        Get.toNamed(RouteConfig.productionDetail,
                            arguments: result['code']);
                      } else if (result['type'] == 2) {
                        Get.toNamed(RouteConfig.equipmentDetail,
                            arguments: result['code']);
                      } else {
                        showDialog(
                            barrierDismissible: false,
                            context: context,
                            builder: (BuildContext context) {
                              return AlertDialog(
                                title: Text('注意'),
                                content: Text('请扫正确的二维码！'),
                                actions: <Widget>[
                                  new Container(
                                    child: FlatButton(
                                      child: new Text(
                                        "确定",
                                        style: TextStyle(color: Colors.red),
                                      ),
                                      onPressed: () {
                                        Navigator.pop(context);
                                      },
                                    ),
                                  ),
                                ],
                              );
                            });
                      }
                    }
                  }
                },
                backgroundColor: Colors.transparent)),
        onWillPop: () async {
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.portraitUp,
          ]);
          OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
          // 点击返回键的操作
          if (lastPopTime == null ||
              DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
            lastPopTime = DateTime.now();
            Fluttertoast.showToast(msg: "再按一次退出");
          } else {
            lastPopTime = DateTime.now();
            // 退出app
            await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
          }
          return false;
        });
  }
}
